import React, { createContext, useContext, useState, useEffect } from 'react';
import { User } from '../models/User';
import * as authService from '../services/authService';
import { Capacitor } from '@capacitor/core';
import { Preferences } from '@capacitor/preferences';

interface AuthContextType {
  user: User | null;
  loading: boolean;
  login: (email: string, password: string) => Promise<void>;
  register: (email: string, password: string, name: string) => Promise<void>;
  logout: () => Promise<void>;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const loadUser = async () => {
      if (Capacitor.isNativePlatform()) {
        const { value } = await Preferences.get({ key: 'user' });
        if (value) setUser(JSON.parse(value));
      } else {
        const storedUser = localStorage.getItem('user');
        if (storedUser) setUser(JSON.parse(storedUser));
      }
      setLoading(false);
    };

    loadUser();
  }, []);

  const saveUser = async (userData: User | null) => {
    setUser(userData);
    if (Capacitor.isNativePlatform()) {
      if (userData) {
        await Preferences.set({ key: 'user', value: JSON.stringify(userData) });
      } else {
        await Preferences.remove({ key: 'user' });
      }
    } else {
      if (userData) {
        localStorage.setItem('user', JSON.stringify(userData));
      } else {
        localStorage.removeItem('user');
      }
    }
  };

  const login = async (email: string, password: string) => {
    try{
      const response = await authService.login(email, password);
      // 从响应头获取 Authorization
      const token = response.headers['authorization'] || response.headers['Authorization'];
      console.log(token)
      if (!token) {
        throw new Error('认证令牌未返回');
      }
      await saveUser(response.data);
    } 
    catch (error) {
      console.error('登录过程中出错:', error);
      throw error;
    }
  };

  const register = async (email: string, password: string, name: string) => {
    const response = await authService.register(email,password,name);
    await saveUser(response.data);
  };


  const logout = async () => {
    await authService.logout();
    await saveUser(null);
  };

  return (
    <AuthContext.Provider value={{ user, loading, login, register, logout }}>
      {children}
    </AuthContext.Provider>
  );
};

export const useAuth = () => {
  const context = useContext(AuthContext);
  if (!context) throw new Error('useAuth must be used within an AuthProvider');
  return context;
};                        